#include "Socket.h"
int createnonblocking()
{
    int listenFd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
    if (listenFd < 0)
    {
        printf("listenfd create error");
        exit(-1);
    }
    return listenFd;
}
Socket::Socket(int fd)
    : fd_(fd)
{
}
int Socket::fd() const
{
    return fd_;
}
void Socket::setreuseaddr(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &opt, static_cast<socklen_t>(sizeof opt));
}
void Socket::setreuseport(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(fd_, SOL_SOCKET, SO_REUSEPORT, &opt, static_cast<socklen_t>(sizeof opt));
}
void Socket::settcpnodelay(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(fd_, SOL_SOCKET, TCP_NODELAY, &opt, static_cast<socklen_t>(sizeof opt));
}
void Socket::setkeepalive(bool on)
{
    int opt = on ? 1 : 0;
    ::setsockopt(fd_, SOL_SOCKET, SO_KEEPALIVE, &opt, static_cast<socklen_t>(sizeof opt));
}
void Socket::bind(const InetAddress &serveraddr)
{
    if (::bind(fd_, serveraddr.addr(), serveraddr.addr_len()) < 0)
    {
        perror("bind() failed");
        close(fd_);
        exit(-1);
    }
}
void Socket::listen(int gblock)
{
    // 因为函数重名了
    if (::listen(fd_, gblock) < 0)
    {
        perror("listen() failed");
        close(fd_);
        exit(-1) ;
    }
}
int Socket::accept(InetAddress& clientaddr)
{
    struct sockaddr_in peeraddr;
    socklen_t len  = sizeof(peeraddr);
    int clientfd = accept4(fd_, (struct sockaddr*)&peeraddr, &len, SOCK_NONBLOCK);
    clientaddr.setAddr(peeraddr);
    return clientfd;
}
Socket::~Socket()
{
    ::close(fd_);
}
